const util = require('util');
const debug = util.debuglog('oil-game:welfare:cache');
const {
  WELFARE_PRIZE,
  PRIZE_RESULT,    //福利时刻奖品
} = require("./consts")

// 获取当前用户
exports.getUserInfo = async function(uid) {
  let user = await this.app.userRemote(uid, 'get', [uid, 'user']);
  return user;
}

//保存当前福利时刻结果
exports.savePrize = async function(uid, prize) {
  debug("uid = %s prize = %s 暂存用户福利时刻结果", uid, prize);
  await this.app.userRemote(uid, "set", [uid, "user.welfare", prize]);

  let redis = this.app.get('redis');
  let key = PRIZE_RESULT+":"+uid;
  //清理福利时刻数据
  await clearWelfareDate.call(this, uid);
  //添加数据到缓存中
  for(let i = 0; i < prize.length; i++){
    await addWelfareData.call(this, uid, i, prize[i]);
  }
}

//获取用户福利时刻结果
exports.getPrize = async function(uid) {
  debug("uid = %s 获取用户抽奖结果", uid);
  //从缓存中获取数据
  let prize = [];
  for(let i = 0; i < WELFARE_PRIZE.length; i++){
    prize.push(await getWelfareData.call(this, uid, i));
  }
  return prize;
}

//更新用户福利抽奖累计石油
exports.addWelfareOil = async function(uid, num) {
  let user = await this.app.userRemote(uid, 'get', [uid, 'user']);
  let welfare_oil = parseInt(user.welfare_oil) + parseInt(num);
  this.app.userRemote(uid, "set", [uid, "user.welfare_oil", welfare_oil]);
}

//添加福利时刻单个奖品
function addWelfareData(uid, index, prize){
  let key = PRIZE_RESULT+":"+uid+":"+index;
  return new Promise((resolve, reject) => {
    redis.hmset(key, prize, function(err, data){   //设置倒计时键
      if(err){
        debug("uid = %s 添加福利时刻数据异常 %s", uid, JSON.stringify(err));
        return reject(err);
      }
      resolve(data);
    });
  });
}

//获取福利时刻单个奖品
function getWelfareData(uid, index){
  let key = PRIZE_RESULT+":"+uid+":"+index;
  return new Promise((resolve, reject) => {
    redis.hgetall(key, function(err, data){   //设置倒计时键
      if(err){
        debug("uid = %s 获取福利时刻数据异常 %s", uid, JSON.stringify(err));
        return reject(err);
      }
      resolve(data);
    });
  });
}

//清理福利时刻数据
function clearWelfareDate(uid){
  let key = PRIZE_RESULT+":"+uid;
  return new Promise((resolve, reject) => {
    for(let i = 0; i < WELFARE_PRIZE.length; i++){
      redis.del(key+":"+i, function(err, data){   //重置抽奖结果
        if(err){
          debug("uid = %s 清理福利时刻数据异常 %s", uid, JSON.stringify(err));
          return reject(err);
        }
        resolve(data);
      });
    }
  });
}
